<?php
/**
 * Created by PhpStorm.
 * User: gqc
 * Date: 2017/1/1
 * Time: 19:55
 */
namespace Api\Service\Amazon;
use Api\Model\Amazon\CommonModel;
use Home\Service\CommonService;
use Inbound\Service\PublicInfoService;

class AccountSellerSkuService extends CommonService{
    protected $accountSellerSkuModel = NULL;
    protected $reportUnsuppressdInventoryModel = NULL;
    protected $prepareneedsService = NULL;
    //查询记录总数
    public $count = 0;
    //页面展示包含页面样式
    public $page = 0;

    public function __construct(){
        $this->accountSellerSkuModel = D('Api/Amazon/AccountSellerSku','Model');
        $this->reportUnsuppressdInventoryModel = D('Api/Amazon/ReportUnsuppressedInventory','Model');
    }

    /**
     * 描述：从api_report_unsuppressed_inventory抓取数据到api_account_seller_sku表中
     * 参数：
     */
    public function insertToAccountSellerSku(){
        $skuData = $this->reportUnsuppressdInventoryModel->selectInsertToAccountSellerSku();
        $this->accountSellerSkuModel->insertData($skuData);
    }
    public function getActualSkuByAccountIdAndSellerSku($accountId, $sellerSku = array()) {
        return $this->accountSellerSkuModel->getActualSkuByAccountIdAndSellerSku($accountId, $sellerSku);
    }
    public function selectSku($date){
        $where = '1';
        if($date['sku']){
            $sku = trim($date['sku']);
            $where .= " AND (`seller_sku` like '%$sku%' OR `fnsku` like '%$sku%' OR `private_sku` like '%$sku%')";
        }
        if($date['asin']){
            $asin = trim($date['asin']);
            $where .= " AND asin = '$asin'";
        }
        if($date['accountId']){
            $where .= " AND `account_id` = ".$date['accountId'];
        }
        if($date['siteId']){
            $where .= " AND `site_id` = ".$date['siteId'];
        }
        if($date['beforetime']){
            $where .= " AND `add_time` >= '".$date['beforetime']."'";
        }
        if($date['aftertime']){
            $where .= " AND `add_time` <= '".$date['aftertime']."'";
        }
        if($date['title']){
            $where .= " AND `title` = ' '";
        }
        $result = $this->accountSellerSkuModel->where($where)->select();
        $this->count = count($result);
        $Page = new \Org\Util\Page($this->count,20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
        $this->page = $Page->show();// 分页显示输出
        $data = $this->accountSellerSkuModel->where($where)->order("add_time desc")
            ->limit($Page->firstRow.','.$Page->listRows)->select();
        return $data;
    }
    public function addSku($arr){
        $data['account_id'] = trim($arr['accountId']);
        $data['site_id'] = trim($arr['siteId']);
        $data['seller_sku'] = htmlspecialchars_decode(trim($arr['sellerSku']));
        $data['fnsku'] = trim($arr['FNsku']);
        $data['private_sku'] = trim(strtoupper($arr['privateSku']));
        $data['asin'] = trim($arr['asin']);
        $data['title'] = trim($arr['title']);
        $data['add_user_id'] = session('current_account.id');
        $data['add_time'] = date('Y-m-d H:i:s',time());
        $data['is_used'] = trim($arr['is_used']);
        $data['first_received_date'] = trim($arr['firsttime']);
        return $this->accountSellerSkuModel->data($data)->add();
    }
    public function updateSku($arr){
        $data['account_id'] = trim($arr['accountId']);
        $data['site_id'] = trim($arr['siteId']);
        $data['seller_sku'] = htmlspecialchars_decode(trim($arr['sellerSku']));
        $data['fnsku'] = trim($arr['FNsku']);
        $data['private_sku'] = trim(strtoupper($arr['privateSku']));
        $data['asin'] = trim($arr['asin']);
        $data['title'] = trim($arr['title']);
        $data['sale_status_id'] = $arr['sale_status_id'];
        $data['add_user_id'] = session('current_account.id');
        $data['update_time'] = date('Y-m-d H:i:s',time());
        $data['is_used'] = trim($arr['is_used']);
        $data['first_received_date'] = trim($arr['firsttime']);
        return $this->accountSellerSkuModel->where('id = '.$arr['id'])->save($data);
    }
    public function delSku($str){
        if($str){
            $data = array(
                'is_used' => 0,
                'add_user_id' => session('current_account.id')
            );
            $str = implode(',',$str);
            $result = $this->accountSellerSkuModel->where('id in ('.$str.')')->setField($data);
            if($result){
                return TRUE;
            }else{
                return FALSE;
          }
        }

    }
    /*
     * @param $datas
     * 检查导入的sku数据合法性
     * khq 2017.1.11
     */
    public function check_upload_data(&$datas, $status = 0)
    {
        if ($status) {
            $saleStatus = PublicInfoService::getSaleStatusName();
            $saleStatusValue = array_flip($saleStatus);
        }

        $flag = true;
        $str  = '';
        foreach ($datas as $k=>&$v){
            if($k==1) continue;
            if($v['A']==''){
                $flag = false;
                $str .= '第'.$k.'行 帐号名称 为空,导入失败\n';
            }
            if($v['B']==''){
                $flag = false;
                $str .= '第'.$k.'行 SellSku 为空,导入失败\n';
            }
            if($v['C']==''){
                $flag = false;
                $str .= '第'.$k.'行 FNSKU 为空,导入失败\n';
            }
            if($v['D']==''){
                $flag = false;
                $str .= '第'.$k.'行 公司内部SKU 为空,导入失败\n';
            }
            if($v['E']==''){
                $flag = false;
                $str .= '第'.$k.'行 ASIN 为空,导入失败\n';
            }
            if($status) {
                if($v['F']==''){
                    $flag = false;
                    $str .= '第'.$k.'行 销售状态 为空,导入失败\n';
                } else {
                    if (!in_array($v['F'], $saleStatus)) {
                        $flag = false;
                        $str .= '第'.$k.'行 销售状态 输入错误,导入失败\n';
                    } else {
                        $v['F'] = $saleStatusValue[$v['F']];
                    }
                }
            } else {
                if($v['F']==''){
                    $flag = false;
                    $str .= '第'.$k.'行 title 为空,导入失败\n';
                }
            }

//            elseif (!$this->check_date_isValid(trim($v['G']))){
//                $flag = false;
//                $str .= '第'.$k.'行 要求日期 格式不正确,导入失败\n';
//            }
        }
        return array(
            'status' => $flag,
            'message'=> $str
        );
    }
    public function upload_platform($arr){
        $message = '';
        $data = array();
        foreach($arr as $k =>$v){
            if($k >= 2){
                $account_id = $this->get_account_id(trim($v['A']));//账号id
                if(!$account_id){
                    $message .='第'.$k.'行'.trim($v['A']).'帐号不存在\n';
                    continue;
                }
                $sellerSku = trim($v['B']);
                $FNSKU = trim($v['C']);
                $privateSku = trim($v['D']);
                $asin = trim($v['E']);
                $title = trim($v['F']);
                $first_received_date = trim($v['G']);
                $data['account_id'] = $account_id;
                $data['site_id'] = D('Api/Amazon/AccountSite','Service')->getSiteIdByAccountId($account_id);
                $data['seller_sku'] = htmlspecialchars_decode($sellerSku);
                $data['fnsku'] = $FNSKU;
                $data['private_sku'] = trim(strtoupper($privateSku));
                $data['asin'] = $asin;
                $data['title'] = $title;
                $data['first_received_date'] = $first_received_date;
                $data['add_user_id'] = session('current_account.id');
                $data['add_time'] = date('Y-m-d H:i:s',time());
                $data['is_used'] = 1;
                if($this->accountIdAndSellerSku($account_id,$sellerSku)){
                    $where = array(
                        'account_id' => $account_id,
                        'seller_sku' => $sellerSku,
                    );
                    $upTitle = $this->accountSellerSkuModel->where($where)->save($data);
                    if($upTitle){
                        $message .='第'.$k.'行'.trim($v['A']).'帐号和sellersku'.trim($v['B']).'更新成功\n';
                    }else{
                        $message .='第'.$k.'行'.trim($v['A']).'帐号和sellersku'.trim($v['B']).'更新失败\n';
                    }

                    continue;
                }


                $result = $this->accountSellerSkuModel->add($data);
                if(!$result){
                    $message .='第'.$k.'行插入失败\n';continue;
                }else{
                    $success = '插入成功';
                }

            }
        }
        $data = $message.$success;
        return $data;
    }

    public function undate_sale_status($arr) {
        $message = '';
        $data = array();
        foreach($arr as $k =>$v){
            if($k >= 2){
                $account_id = $this->get_account_id(trim($v['A']));//账号id
                if(!$account_id){
                    $message .='第'.$k.'行'.trim($v['A']).'帐号不存在\n';
                    continue;
                }
                $sellerSku = trim($v['B']);
                $FNSKU = trim($v['C']);
                $privateSku = trim($v['D']);
                $asin = trim($v['E']);
                $sale_status_id = $v['F'];
                $data['account_id'] = $account_id;
                $data['seller_sku'] = htmlspecialchars_decode($sellerSku);
                $data['fnsku'] = $FNSKU;
                $data['private_sku'] = trim(strtoupper($privateSku));
                $data['asin'] = $asin;
                $data['sale_status_id'] = $sale_status_id;

                if($this->accountIdAndSellerSku($account_id,$sellerSku)){
                    $where = array(
                        'account_id' => $account_id,
                        'seller_sku' => $sellerSku,
                    );
                    $upStatus = $this->accountSellerSkuModel->where($where)->save($data);
                    if($upStatus){
                        $message .='第'.$k.'行'.trim($v['A']).'帐号和sellersku'.trim($v['B']).'销售状态更新成功\n';
                    }else{
                        $message .='第'.$k.'行'.trim($v['A']).'帐号和sellersku'.trim($v['B']).'销售状态更新失败\n';
                    }

                    continue;
                } else {
                    $message .='第'.$k.'行'.trim($v['A']).'帐号和sellersku'.trim($v['B']). '未录入系统\n';
                }


            }
        }
        $data = $message;
        return $data;
    }

    /*
     * 拉取title
     * */
    public function getTitle($accountId){
        //$message = '';
        $successNum = 0;
        $errorNum = 0;
        $inNum = 0;
        $result = D('Api/Amazon/Title','Service')->getTitle($accountId);
        if($result){
            foreach($result as $k =>$v){

                if(empty($v['account_id']) || empty($v['seller_sku']) || empty($v['title'])){
                    $errorNum +=1 ;
                    continue;
                }
                if(preg_match('/\b[A-z]\d[A-z]\d/',$v['seller_sku']) || strstr($v['seller_sku'],'SHUADAN')){
                    continue;
                }
                $seller_sku = $v['seller_sku'];
                $accountId = $v['account_id'];
                $data['title'] = CommonModel::slashesDeep($v['title']);
                $data['asin'] = $v['asin'];
                if($this->accountSellerSkuModel->where("`account_id` = $accountId AND `seller_sku` = '$seller_sku'")->getField('id')){
                    $err = $this->accountSellerSkuModel->where("`account_id` = $accountId AND `seller_sku` = '$seller_sku'")->save($data);
                    if($err){
                        $successNum +=1 ;
                    }else{
                        $errorNum +=1 ;
                    }
                }else{
                    $add = array(
                        'account_id' => $v['account_id'],
                        'seller_sku' => trim($v['seller_sku']),
                        'title' => $v['title'],
                        'asin' => $v['asin']?$v['asin']:'',
                        'site_id' => PublicInfoService::get_siteid_by_accountid($v['account_id']),
                        'add_user_id' => session('current_account.id'),
                        'add_time' => date('Y-m-d H:i:s'),
                        'is_used' => 1,
                    );
                    $in = $this->accountSellerSkuModel->add($add);
                    if($in){
                        $inNum +=1;
                    }else{
                        $errorNum +=1;
                        continue;
                    }

                }
            }
            $message = "title共拉取".count($result)."个,更新成功 $successNum 个,新增成功 $inNum 个，失败 $errorNum 个";
        }else{
            $message = '拉取title接口链接失败';
        }
        //print_r($this->accountSellerSkuModel->getLastSql());die;
        return $message;

    }
    /**
     * 时间检验
    */
    function check_date_isValid($date, $formats = array("Y-m-d", "Y/m/d"))
    {
        $unixTime = strtotime($date);
        if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
            return false;
        }
        //校验日期的有效性，只要满足其中一个格式就OK
        foreach ($formats as $format) {
            if (date($format, $unixTime) == date("Y/m/d",$unixTime)) {
                return true;
            }
        }
        return false;
    }
    /*
     * 检查是否有重复的帐号和Sellersku
     * */
    public function accountIdAndSellerSku($accountId,$sellerSku){
        return $this->accountSellerSkuModel->where("account_id = $accountId AND seller_sku = '$sellerSku'")->getField('id');
    }
    /*
     * 检查帐号是否存在
     * */
    public function get_account_id($name)
    {
        return M('amazonorder_accounts',' ','fbawarehouse')
            ->where("name ='$name'")
            ->getField('id');
    }

    /**
     * @param $accountId
     * @param array $sellerSku
     * @return mixed
     * 通过sellersku找asin
     */
    public function getAsinBySellerSku ($accountId, $sellerSku = array()) {
        return $this->accountSellerSkuModel->getAsinBySellerSku ($accountId, $sellerSku = array());
    }
    /**
     * 描述: 检测内部sku是否存在
     * 作者: kelvin
     */
    public function checkSku($sku) {
        return M('skusystem_skus',' ','fbawarehouse')
            ->where("sku ='$sku'")
            ->getField('id');
    }

    public function downloadAllSku() {
        $sku = $this->accountSellerSkuModel->getAllSku();
        return !(empty($sku)) ? $sku : array();
    }
}